document.addEventListener("DOMContentLoaded", () => {
  const smoothScrollButtons = document.querySelectorAll("[data-scroll]");
  const floatingNav = document.querySelector(".floating-nav");
  const timelineTemplate = document.getElementById("timeline-template");
  const timelineDetails = document.getElementById("timeline-details");
  const osTemplate = document.getElementById("os-template");
  const osTable = document.getElementById("os-table");
  const modeTemplate = document.getElementById("mode-template");
  const modeList = document.getElementById("mode-list");
  const stageSlider = document.getElementById("stage-slider");
  const stageOutput = document.getElementById("stage-output");
  const languageSlider = document.getElementById("language-slider");
  const langCompare = document.getElementById("lang-compare");

  const clamp = (value, min, max) => Math.min(Math.max(value, min), max);

  // Smooth scroll handler
  smoothScrollButtons.forEach((btn) => {
    btn.addEventListener("click", () => {
      const target = document.querySelector(btn.dataset.scroll);
      if (target) {
        target.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    });
  });

  // Timeline interactions
  if (timelineTemplate && timelineDetails) {
    const phases = {};
    timelineTemplate.content.querySelectorAll("div[data-phase]").forEach((el) => {
      phases[el.dataset.phase] = el.cloneNode(true);
    });

    const renderPhase = (phase) => {
      const fragment = phases[phase];
      if (!fragment) return;
      timelineDetails.innerHTML = "";
      timelineDetails.appendChild(fragment);
    };

    renderPhase("phase0");

    document.querySelectorAll(".timeline__item").forEach((item) => {
      item.addEventListener("click", () => {
        document
          .querySelectorAll(".timeline__item")
          .forEach((el) => el.classList.remove("timeline__item--active"));
        item.classList.add("timeline__item--active");
        renderPhase(item.dataset.timeline);
      });
    });
  }

  // Tab switching (Git/GitHub/Gitee)
  document.querySelectorAll(".tab-group").forEach((group) => {
    group.querySelectorAll(".tab").forEach((tab) => {
      tab.addEventListener("click", () => {
        group.querySelectorAll(".tab").forEach((btn) => {
          btn.classList.remove("tab--active");
          btn.setAttribute("aria-selected", "false");
        });
        tab.classList.add("tab--active");
        tab.setAttribute("aria-selected", "true");

        const key = tab.dataset.tab;
        document.querySelectorAll(".tab-panel").forEach((panel) => {
          panel.classList.toggle(
            "tab-panel--active",
            panel.id === `tab-${key}`
          );
        });
      });
    });
  });

  // Panel switcher (Compiler/Interpreter/Runtime)
  document.querySelectorAll(".switcher__btn").forEach((button) => {
    button.addEventListener("click", () => {
      document
        .querySelectorAll(".switcher__btn")
        .forEach((btn) => btn.classList.remove("switcher__btn--active"));
      button.classList.add("switcher__btn--active");

      const key = button.dataset.panel;
      document.querySelectorAll(".panel").forEach((panel) => {
        panel.classList.toggle(
          "panel--active",
          panel.id === `panel-${key}`
        );
      });
    });
  });

  // Operating system comparison
  if (osTemplate && osTable) {
    const osMap = {};
    osTemplate.content.querySelectorAll("div[data-os]").forEach((el) => {
      osMap[el.dataset.os] = el.cloneNode(true);
    });

    const renderOS = (key) => {
      const fragment = osMap[key];
      if (!fragment) return;
      osTable.innerHTML = "";
      osTable.appendChild(fragment);
    };

    renderOS("daily");

    document.querySelectorAll(".pill").forEach((pill) => {
      pill.addEventListener("click", () => {
        document
          .querySelectorAll(".pill")
          .forEach((el) => el.classList.remove("pill--active"));
        pill.classList.add("pill--active");
        renderOS(pill.dataset.os);
      });
    });
  }

  // Accordion interactions
  document.querySelectorAll(".accordion__item").forEach((item) => {
    const trigger = item.querySelector(".accordion__trigger");
    const content = item.querySelector(".accordion__content");
    if (!trigger || !content) return;

    if (item.classList.contains("accordion__item--open")) {
      content.style.maxHeight = `${content.scrollHeight}px`;
    }

    trigger.addEventListener("click", () => {
      const isOpen = item.classList.contains("accordion__item--open");
      document.querySelectorAll(".accordion__item").forEach((el) => {
        el.classList.remove("accordion__item--open");
        const inner = el.querySelector(".accordion__content");
        if (inner) inner.style.maxHeight = null;
      });

      if (!isOpen) {
        item.classList.add("accordion__item--open");
        content.style.maxHeight = `${content.scrollHeight}px`;
      }
    });
  });

  // Mode toggle (language vs algorithm)
  if (modeTemplate && modeList) {
    const modeMap = {};
    modeTemplate.content.querySelectorAll("div[data-mode]").forEach((el) => {
      const key = el.dataset.mode;
      const items = Array.from(el.querySelectorAll("li")).map((li) => li.textContent);
      modeMap[key] = items;
    });

    const renderMode = (key) => {
      const items = modeMap[key];
      if (!items) return;
      modeList.innerHTML = items.map((item) => `<li>${item}</li>`).join("");
    };

    renderMode("language");

    document.querySelectorAll(".mode-toggle__btn").forEach((btn) => {
      btn.addEventListener("click", () => {
        document
          .querySelectorAll(".mode-toggle__btn")
          .forEach((el) => el.classList.remove("mode-toggle__btn--active"));
        btn.classList.add("mode-toggle__btn--active");
        renderMode(btn.dataset.mode);
      });
    });
  }

  // Stage slider suggestions
  if (stageSlider && stageOutput) {
    const stageText = [
      "阶段 0 · 电脑素养打底，建议熟悉文件系统、快捷键、基础网络概念。",
      "阶段 1 · 刚开始学习编程，完成 Hello World、条件循环、小项目。",
      "阶段 2 · 深入算法与数据结构，建立刷题节奏并复盘总结。",
      "阶段 3 · 参与团队项目，掌握协作、测试、部署与运维。",
      "阶段 4 · 关注安全与 AI 前沿，搭建自动化与终身学习体系。",
    ];

    stageSlider.addEventListener("input", () => {
      const idx = clamp(parseInt(stageSlider.value, 10), 0, stageText.length - 1);
      stageOutput.textContent = stageText[idx];
    });
  }

  // Language slider visual feedback
  if (languageSlider && langCompare) {
    const updateBias = () => {
      const value = clamp(parseInt(languageSlider.value, 10), 0, 100);
      const bias = value / 100;
      langCompare.style.setProperty("--bias", bias);
      langCompare.querySelectorAll(".compare__item").forEach((item, index) => {
        const intensity = index === 0 ? 1 - bias : bias;
        item.style.background = `rgba(37, 99, 235, ${0.12 + intensity * 0.12})`;
        item.style.borderColor = `rgba(37, 99, 235, ${0.18 + intensity * 0.22})`;
      });
    };
    updateBias();
    languageSlider.addEventListener("input", updateBias);
  }

  // Active section highlight in nav
  const sectionObserver = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const id = `#${entry.target.id}`;
          document
            .querySelectorAll(".floating-nav button")
            .forEach((btn) => btn.classList.toggle("is-active", btn.dataset.scroll === id));
        }
      });
    },
    {
      rootMargin: "-60% 0px -30% 0px",
      threshold: 0,
    }
  );

  document.querySelectorAll("main > section").forEach((section) => {
    sectionObserver.observe(section);
  });

  // Compact navigation when scrolling
  if (floatingNav) {
    let lastScroll = 0;
    window.addEventListener("scroll", () => {
      const current = window.pageYOffset || document.documentElement.scrollTop;
      if (current > lastScroll && current > 200) {
        floatingNav.classList.add("floating-nav--compact");
      } else {
        floatingNav.classList.remove("floating-nav--compact");
      }
      lastScroll = current;
    });
  }
});
